﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Web;

namespace fgbt_move
{
    public class UTSeedInfo
    {
        public string HASH = "";
        public Int64 UploadSpeed = 0;
        public int SeedInSwarm = 0;
        public string RawString = "";
        public int SeedStatus = 0;
        public DateTime SeedAddOn = DateTime.Now;
    }
    public class UTControl
    {
        /// <summary>
        /// 清理已经完成的种子
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static int RemoveFinishedSeeds(string url, string username, string password)
        {
            //url处理
            if (url.Length < 10) return -1;
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";
            List<UTSeedInfo> utseeds = new List<UTSeedInfo>();

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {
                //获取种子列表
                string c = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&list=1", url, uttoken), ref utcookie, username, password);
                //Regex r1 = new Regex(@"\[""(?<uthash>\w{40})"",(?<utstatus>\d*?),(.*?,){6}(?<utupspeed>\d*?),(.*?,){6}(?<utseedinswarm>\d*?),.*?]");
                Regex r1 = new Regex(@"\[""(?<uthash>\w{40})"",(?<utstatus>\d*?),(.*?,){6}(?<utupspeed>\d*?),(.*?,){6}(?<utseedinswarm>\d*?),(.*?,){7}(?<utseedaddon>\d*?),.*?]");
                if (r1.IsMatch(c))
                {
                    foreach (Match match in r1.Matches(c))
                    {
                        try
                        {
                            UTSeedInfo utseed = new UTSeedInfo();
                            utseed.RawString = match.Value;
                            utseed.HASH = match.Groups["uthash"].Value;
                            utseed.UploadSpeed = Int64.Parse(match.Groups["utupspeed"].Value);
                            utseed.SeedInSwarm = int.Parse(match.Groups["utseedinswarm"].Value);
                            utseed.SeedStatus = int.Parse(match.Groups["utstatus"].Value);
                            utseed.SeedAddOn = DateTime.Parse("1970.1.1").AddSeconds(Int64.Parse(match.Groups["utseedaddon"].Value));
                            utseeds.Add(utseed);
                        }
                        catch (System.Exception ex)
                        {
                            WorkLog.Add(3, "删除完成的下载_读取种子信息出错" + ex.Message);
                            continue;
                        }
                    }
                }

                foreach (UTSeedInfo utseed in utseeds)
                {
                    if ((DateTime.Now - utseed.SeedAddOn).TotalDays > 7 && (DateTime.Now - utseed.SeedAddOn).TotalDays < 11)
                    {
                        //删除添加时间在7天以前的种子
                        DeleteSeed(utseed.HASH, url, utcookie, uttoken, username, password);
                    }
                    if (utseed.SeedStatus == 136)
                    {
                        //防止因为磁盘掉线，不能启用自动删除种子功能，否则种子将被全部删除
                        //删除下载完成的种子
                        //DeleteSeed(utseed.HASH, url, utcookie, uttoken, username, password);
                    }
                }
            }

            return 0;
        }

        /// <summary>
        /// 维护活动种子列表，每次执行：
        /// 当活动上传大于25个时，停止一个种子数最多的且种子数大于5的种子
        /// 当活动上传小于18个时，开启一个停止的种子
        /// 删除一个错误的种子
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static int MaintenanceActiveSeeds(string url, string username, string password)
        {
            //url处理
            if (url.Length < 10) return -1;
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";
            List<UTSeedInfo> utseeds = new List<UTSeedInfo>();

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {
                //获取种子列表
                string c = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&list=1", url, uttoken), ref utcookie, username, password);
                //new Regex(@"\[""(?<uthash>\w{40})"",(?<utstatus>\d*?),(.*?,){6}(?<utupspeed>\d*?),(.*?,){6}(?<utseedinswarm>\d*?),(.*?,){7}(?<utseedaddon>\d*?),.*?]")
                //new Regex(@"\[""(?<uthash>\w{40})"",(?<utstatus>\d*?),(.*?,){6}(?<utupspeed>\d*?),(.*?,){6}(?<utseedinswarm>\d*?),.*?]");
                Regex r1 = new Regex(@"\[""(?<uthash>\w{40})"",(?<utstatus>\d*?),(.*?,){6}(?<utupspeed>\d*?),(.*?,){6}(?<utseedinswarm>\d*?),(.*?,){7}(?<utseedaddon>\d*?),.*?]");
                if (r1.IsMatch(c))
                {
                    foreach (Match match in r1.Matches(c))
                    {
                        try
                        {
                            UTSeedInfo utseed = new UTSeedInfo();
                            utseed.RawString = match.Value;
                            utseed.HASH = match.Groups["uthash"].Value;
                            utseed.UploadSpeed = Int64.Parse(match.Groups["utupspeed"].Value);
                            utseed.SeedInSwarm = int.Parse(match.Groups["utseedinswarm"].Value);
                            utseed.SeedStatus = int.Parse(match.Groups["utstatus"].Value);
                            utseed.SeedAddOn = DateTime.Parse("1970.1.1").AddSeconds(Int64.Parse(match.Groups["utseedaddon"].Value));
                            utseeds.Add(utseed);
                        }
                        catch (System.Exception ex)
                        {
                            WorkLog.Add(3, "维护上传列表_读取种子信息出错" + ex.Message);
                            continue;
                        }
                    }
                }

                //统计上传速度大于5kb/s的种子数、拥有最多种子的种子所拥有的种子数，hash
                int activeupcount = 0;
                int maxseed = 10;
                string maxseedhash = "";
                string stoppedhash = "";
                foreach (UTSeedInfo utseed in utseeds)
                {
                    if (utseed.SeedStatus == 201)
                    {
                        if (utseed.UploadSpeed > 4096)
                        {
                            activeupcount++;
                        }
                        if (utseed.UploadSpeed > 1000)
                        {
                            if (utseed.SeedInSwarm > maxseed)
                            {
                                maxseed = utseed.SeedInSwarm;
                                maxseedhash = utseed.HASH;
                                utseed.UploadSpeed = -1;
                            }
                        }
                    }
                    else if (utseed.SeedStatus == 152)
                    {
                        //防止因为磁盘掉线，不能启用自动删除种子功能，否则种子将被全部删除
                        //删除种子
                        //DeleteSeed(utseed.HASH, url, utcookie, uttoken, username, password);
                    }
                    else if (utseed.SeedStatus == 136)
                    {
                        stoppedhash = utseed.HASH;
                    }

                    if ((DateTime.Now - utseed.SeedAddOn).TotalDays > 30 && (DateTime.Now - utseed.SeedAddOn).TotalDays < 34)
                    {
                        //删除添加时间在30天以前的种子
                        DeleteSeed(utseed.HASH, url, utcookie, uttoken, username, password);
                    }
                }

                //各项阈值随时间调整，夜间放宽限制

                int topactivecount = 25; //快速停止种子阈值
                int maxactivecount = 20; //停止种子阈值
                int minactivecount = 15; //开启种子阈值
                int lowactivecount = 10; //快速开启种子阈值

                if (DateTime.Now.Hour >= 0 && DateTime.Now.Hour <= 0)
                {
                    //午夜12点到1点，逐渐开启
                    topactivecount = 70; //快速停止种子阈值
                    maxactivecount = 60; //停止种子阈值
                    minactivecount = 50; //开启种子阈值
                    lowactivecount = 15; //快速开启种子阈值
                }
                else if (DateTime.Now.Hour >= 1 && DateTime.Now.Hour <= 6)
                {
                    //凌晨1~7点，保持
                    topactivecount = 80; //快速停止种子阈值
                    maxactivecount = 70; //停止种子阈值
                    minactivecount = 60; //开启种子阈值
                    lowactivecount = 50; //快速开启种子阈值
                }
                else if (DateTime.Now.Hour >= 7 && DateTime.Now.Hour <= 9)
                {
                    //早上7~10点，不再开启
                    topactivecount = 80; //快速停止种子阈值
                    maxactivecount = 70; //停止种子阈值
                    minactivecount = 20; //开启种子阈值
                    lowactivecount = 15; //快速开启种子阈值
                }
                else if (DateTime.Now.Hour >= 10 && DateTime.Now.Hour <= 11)
                {
                    //上午10~12点，逐渐停止
                    topactivecount = 80; //快速停止种子阈值
                    maxactivecount = 30; //停止种子阈值
                    minactivecount = 20; //开启种子阈值
                    lowactivecount = 15; //快速开启种子阈值
                }

                if (activeupcount > topactivecount)
                {
                    //停止maxseedhash直到activeupcount小于等于20
                    for (int i = 0; i < 5; i++)
                    {
                        if (activeupcount <= maxactivecount) break;
                        if (maxseedhash != "") StopSeed(maxseedhash, url, utcookie, uttoken, username, password);
                        else break;

                        maxseed = 10;
                        activeupcount = 0;
                        maxseedhash = "";

                        foreach (UTSeedInfo utseed in utseeds)
                        {
                            if (utseed.SeedStatus == 201)
                            {
                                if (utseed.UploadSpeed > 4096)
                                {
                                    activeupcount++;
                                }
                                if (utseed.UploadSpeed > 1000)
                                {
                                    if (utseed.SeedInSwarm > maxseed)
                                    {
                                        maxseed = utseed.SeedInSwarm;
                                        maxseedhash = utseed.HASH;
                                        utseed.UploadSpeed = -1;
                                    }
                                }
                            }
                        }
                    }
                }
                if (activeupcount > maxactivecount)
                {
                    //停止maxseedhash的种子

                    if (maxseedhash != "") StopSeed(maxseedhash, url, utcookie, uttoken, username, password);
                }
                else if (activeupcount < minactivecount)
                {
                    //开启stoppedhash的种子
                    if (stoppedhash != "") StartSeed(stoppedhash, url, utcookie, uttoken, username, password);
                }
                else if (activeupcount < lowactivecount)
                {
                    //开启10个stoppedhash的种子
                    int i = 0;
                    foreach (UTSeedInfo utseed in utseeds)
                    {
                        if (utseed.SeedStatus == 136)
                        {
                            if (utseed.HASH != "") StartSeed(utseed.HASH, url, utcookie, uttoken, username, password);
                            if (++i > 9) break;
                        }
                    }

                }

            }

            return 0;
        }

        /// <summary>
        /// 停止种子
        /// </summary>
        /// <param name="HASH"></param>
        /// <param name="url"></param>
        /// <param name="utcookie"></param>
        /// <param name="uttoken"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool StopSeed(string HASH, string url, CookieCollection utcookie, string uttoken, string username, string password)
        {
            string d = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&action=stop&hash={2}", url, uttoken, HASH), ref utcookie, username, password);

            if (d.IndexOf("{\"build\":") >= 0)
            {
                //WorkLog.Add(9, string.Format("停止UT上传，HASH值为{0}", HASH));
                return true;
            }
            else
            {
                WorkLog.Add(3, string.Format("停止UT上传失败，HASH值为{0}", HASH));
                return true;
            }
        }
        /// <summary>
        /// 开始种子
        /// </summary>
        /// <param name="HASH"></param>
        /// <param name="url"></param>
        /// <param name="utcookie"></param>
        /// <param name="uttoken"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool StartSeed(string HASH, string url, CookieCollection utcookie, string uttoken, string username, string password)
        {
            string d = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&action=start&hash={2}", url, uttoken, HASH), ref utcookie, username, password);

            if (d.IndexOf("{\"build\":") >= 0)
            {
                //WorkLog.Add(9, string.Format("开始UT上传，HASH值为{0}", HASH));
                return true;
            }
            else
            {
                WorkLog.Add(3, string.Format("开始UT上传失败，HASH值为{0}", HASH));
                return true;
            }
        }
        /// <summary>
        /// 删除种子
        /// </summary>
        /// <param name="HASH"></param>
        /// <param name="url"></param>
        /// <param name="utcookie"></param>
        /// <param name="uttoken"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool DeleteSeed(string HASH, string url, CookieCollection utcookie, string uttoken, string username, string password)
        {
            string d = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&action=remove&hash={2}", url, uttoken, HASH), ref utcookie, username, password);

            if (d.IndexOf("{\"build\":") >= 0)
            {
                //WorkLog.Add(9, string.Format("删除UT上传，HASH值为{0}", HASH));
                return true;
            }
            else
            {
                WorkLog.Add(3, string.Format("删除UT上传失败，HASH值为{0}", HASH));
                return true;
            }
        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="url"></param>
        /// <param name="utcookie"></param>
        /// <param name="uttoken"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool GetUTToken(string url, ref CookieCollection utcookie, ref string uttoken, string username, string password)
        {
            string a = WebAccess.GetWebResponse(url + "gui/token.html", ref utcookie, username, password);
            if (a.IndexOf("<html><div id='token' style='display:none;'>") >= 0)
            {
                uttoken = a.Replace("<html><div id='token' style='display:none;'>", "").Replace("</div></html>", "");
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取UT的默认下载目录
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string GetUTSaveDir(string url, string username, string password)
        {
            //url处理
            if (url.Length < 10) return "null";
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {
                string c = WebAccess.GetWebResponse(url + "gui/?action=getsettings&token=" + uttoken, ref utcookie, username, password);


                Regex r1 = new Regex(@"""dir_active_download"",\d,""(?<value>.*?)""");
                if (r1.IsMatch(c))
                {
                    string d = r1.Match(c).Groups["value"].Value;
                    d = d.Replace("\\\\", "\\");
                    return d;
                }
            }
            return "null";
        }
        /// <summary>
        /// 更改UT的默认下载目录
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="newSaveDir"></param>
        /// <returns></returns>
        public static string SetUTSaveDir(string url, string username, string password, string newSaveDir)
        {
            //url处理
            if (url.Length < 10) return "null";
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";
            //必须符合url的要求
            newSaveDir = WebAccess.EncodePost(newSaveDir);

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {

                string c = WebAccess.GetWebResponse(url + "gui/?" + "token=" + uttoken + "&action=setsetting&s=dir_active_download&v=" + newSaveDir, ref utcookie, username, password);

                if (GetUTSaveDir(url, username, password) == System.Web.HttpUtility.UrlDecode(newSaveDir)) return newSaveDir;
                else return "null";
            }
            return "null";
        }


        /// <summary>
        /// 获取UT的下载完成后移动到目录
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string GetUTMoveDir(string url, string username, string password)
        {
            //url处理
            if (url.Length < 10) return "null";
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {
                string c = WebAccess.GetWebResponse(url + "gui/?action=getsettings&token=" + uttoken, ref utcookie, username, password);


                Regex r1 = new Regex(@"""dir_completed_download"",\d,""(?<value>.*?)""");
                if (r1.IsMatch(c))
                {
                    string d = r1.Match(c).Groups["value"].Value;
                    d = d.Replace("\\\\", "\\");
                    return d;
                }
            }
            return "null";
        }
        /// <summary>
        /// 更改UT的下载完成后移动到目录
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="newSaveDir"></param>
        /// <returns></returns>
        public static string SetUTMoveDir(string url, string username, string password, string newSaveDir)
        {
            //url处理
            if (url.Length < 10) return "null";
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";
            //必须符合url的要求
            newSaveDir = WebAccess.EncodePost(newSaveDir);

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {

                string c = WebAccess.GetWebResponse(url + "gui/?" + "token=" + uttoken + "&action=setsetting&s=dir_completed_download&v=" + newSaveDir, ref utcookie, username, password);

                if (GetUTMoveDir(url, username, password) == System.Web.HttpUtility.UrlDecode(newSaveDir)) return newSaveDir;
                else return "null";
            }
            return "null";
        }
        /// <summary>
        /// 暂停Pub上传下载（实际为设置上传下载速度为1，ut默认必须为计划任务状态）
        /// </summary>
        public static void SetPubUTPause()
        {
            //if (Config.ASConfig.PubUt_WebUIUrl != "" && Config.ASConfig.PubUt_WebUIUsername != "" && Config.ASConfig.PubUt_WebUIPassword != "")
            //{
            //    if (SetUTPause(Config.ASConfig.PubUt_WebUIUrl, Config.ASConfig.PubUt_WebUIUsername, Config.ASConfig.PubUt_WebUIPassword, 200) != "OK")
            //    {
            //        WorkLog.Add(0, "恢复PubUT上传下载失败");
            //    }
            //}
            //else
            //{
            //    WorkLog.Add(0, "恢复PubUT上传下载失败:配置信息不全");
            //}
        }
        /// <summary>
        /// 暂停Rss上传下载（实际为设置上传下载速度为1，ut默认必须为计划任务状态）
        /// </summary>
        public static void SetRssUTPause()
        {
            //if (Config.ASConfig.RssUt_WebUIUrl != "" && Config.ASConfig.RssUt_WebUIUsername != "" && Config.ASConfig.RssUt_WebUIPassword != "")
            //{
            //    if (SetUTPause(Config.ASConfig.RssUt_WebUIUrl, Config.ASConfig.RssUt_WebUIUsername, Config.ASConfig.RssUt_WebUIPassword) != "OK")
            //    {
            //        WorkLog.Add(0, "暂停RssUT上传下载失败");
            //    }
            //}
            //else
            //{
            //    WorkLog.Add(0, "暂停RssUT上传下载失败:配置信息不全");
            //}
        }
        /// <summary>
        /// 暂停上传下载（实际为设置上传下载速度为1，ut默认必须为计划任务状态）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string SetUTPause(string url, string username, string password)
        {
            //url处理
            if (url.Length < 10) return null;
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {

                string c = WebAccess.GetWebResponse(url + "gui/?" + "token=" + uttoken + "&action=setsetting&s=sched_ul_rate&v=1&s=sched_dl_rate&v=1", ref utcookie, username, password);

                if (c.IndexOf("{\"build\":") >= 0)
                {
                    return "OK";
                }
            }
            return null;
        }
        /// <summary>
        /// 暂停上传下载（实际为设置上传下载速度为1，ut默认必须为计划任务状态）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string SetUTPause(string url, string username, string password, int speedlimit)
        {
            //url处理
            if (url.Length < 10) return null;
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {

                string c = WebAccess.GetWebResponse(url + "gui/?" + "token=" + uttoken + "&action=setsetting&s=sched_ul_rate&v=" + speedlimit.ToString() + "&s=sched_dl_rate&v=" + speedlimit.ToString(), ref utcookie, username, password);

                if (c.IndexOf("{\"build\":") >= 0)
                {
                    return "OK";
                }
            }
            return null;
        }
        /// <summary>
        /// 恢复Pub上传下载（实际为设置上传下载速度为空，ut默认必须为计划任务状态）
        /// </summary>
        public static void SetPubUTStart()
        {
            //if (Config.ASConfig.PubUt_WebUIUrl != "" && Config.ASConfig.PubUt_WebUIUsername != "" && Config.ASConfig.PubUt_WebUIPassword != "")
            //{
            //    if (SetUTSpeed(Config.ASConfig.PubUt_WebUIUrl, Config.ASConfig.PubUt_WebUIUsername, Config.ASConfig.PubUt_WebUIPassword, 0, 0) != "OK")
            //    {
            //        WorkLog.Add(0, "恢复PubUT上传下载失败");
            //    }
            //}
            //else
            //{
            //    WorkLog.Add(0, "恢复PubUT上传下载失败:配置信息不全");
            //}
        }
        /// <summary>
        /// 恢复Rss上传下载（实际为设置上传下载速度为空，ut默认必须为计划任务状态）
        /// </summary>
        public static void SetRssUTStart()
        {
            //if (Config.ASConfig.RssUt_WebUIUrl != "" && Config.ASConfig.RssUt_WebUIUsername != "" && Config.ASConfig.RssUt_WebUIPassword != "")
            //{
            //    if (SetUTSpeed(Config.ASConfig.RssUt_WebUIUrl, Config.ASConfig.RssUt_WebUIUsername, Config.ASConfig.RssUt_WebUIPassword, Config.ASConfig.RssUt_UploadSpeed, Config.ASConfig.RssUt_DownloadSpeed) != "OK")
            //    {
            //        WorkLog.Add(0, "恢复RssUT上传下载失败");
            //    }
            //}
            //else
            //{
            //    WorkLog.Add(0, "恢复RssUT上传下载失败:配置信息不全");
            //}
            ////WorkLog.Add(3,string.Format("恢复速度为下载{0}上传{1}", Config.ASConfig.RssUt_DownloadSpeed, Config.ASConfig.RssUt_UploadSpeed));
        }
        /// <summary>
        /// 恢复上传下载（实际为设置上传下载速度为系统设置值，ut默认必须为计划任务状态）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string SetUTStart(string url, string username, string password)
        {
            ////url处理
            //if (url.Length < 10) return null;
            //if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            //CookieCollection utcookie = new CookieCollection();
            //string uttoken = "";

            //if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            //{
            //    string c = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&action=setsetting&s=sched_ul_rate&v=0&s=sched_dl_rate&v={2}", url, uttoken, Config.ASConfig.RssUt_DownloadSpeed) , ref utcookie, username, password);

            //    if (c.IndexOf("{\"build\":") >= 0)
            //    {
            //        return "OK";
            //    }
            //}
            return null;
        }
        /// <summary>
        /// 设置ut的上传下载速度（ut默认必须为计划任务状态，0表示不限速）
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="upspeed"></param>
        /// <param name="downspeed"></param>
        /// <returns></returns>
        public static string SetUTSpeed(string url, string username, string password, int upspeed, int downspeed)
        {
            //url处理
            if (url.Length < 10) return null;
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            //速度处理
            string up = (upspeed == 0) ? "0" : upspeed.ToString();
            string down = (downspeed == 0) ? "0" : downspeed.ToString();

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {
                string c = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&action=setsetting&s=sched_ul_rate&v={2}&s=sched_dl_rate&v={3}", url, uttoken, up, down), ref utcookie, username, password);

                if (c.IndexOf("{\"build\":") >= 0)
                {
                    return "OK";
                }
            }
            return null;
        }

        /// <summary>
        /// 恢复出问题的UT下载
        /// </summary>
        public static void ResumeErrorSeeds()
        {
            //ResumeErrorSeeds(Config.ASConfig.RssUt_WebUIUrl, Config.ASConfig.RssUt_WebUIUsername, Config.ASConfig.RssUt_WebUIPassword);
        }

        /// <summary>
        /// 恢复出问题的UT下载
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public static void ResumeErrorSeeds(string url, string username, string password)
        {
            //url处理
            if (url.Length < 10) return;
            if (url.Substring(url.Length - 1, 1) != "/") url += "/";

            CookieCollection utcookie = new CookieCollection();
            string uttoken = "";

            if (GetUTToken(url, ref utcookie, ref uttoken, username, password))
            {
                string c = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&list=1", url, uttoken), ref utcookie, username, password);

                if (c.IndexOf("\"torrents\":") >= 0)
                {
                    //出错后的状态值：152，不需要校验
                    Regex r1 = new Regex(@"\[""\w{40}"",152,""[^\""]*?"",\d*,\d{1,3},");
                    if (r1.IsMatch(c))
                    {
                        //获取出错种子列表
                        GroupCollection gp = r1.Match(c).Groups;
                        for (int i = 0; i < gp.Count; i++)
                        {
                            if (gp[i].Success)
                            {
                                string tmp = gp[i].Value;
                                Regex r2 = new Regex(@"\w{40}");
                                if (r2.IsMatch(tmp))
                                {
                                    //获取HASH
                                    tmp = r2.Match(tmp).Value;

                                    //恢复UT下载
                                    string d = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&action=start&hash={2}", url, uttoken, tmp), ref utcookie, username, password);

                                    if (d.IndexOf("{\"build\":") >= 0)
                                    {
                                        //WorkLog.Add(9, string.Format("恢复UT下载，HASH值为{0}", tmp));
                                        return;
                                    }
                                    else WorkLog.Add(3, "恢复UT下载失败1");
                                }
                                else WorkLog.Add(3, "恢复UT下载失败2");
                            }
                            else WorkLog.Add(3, "恢复UT下载失败3");
                        }
                    }

                    //出错后的状态值：144，需要校验
                    r1 = new Regex(@"\[""\w{40}"",144,""[^\""]*?"",\d*,\d{1,3},");
                    if (r1.IsMatch(c))
                    {
                        //获取出错种子列表
                        GroupCollection gp = r1.Match(c).Groups;
                        for (int i = 0; i < gp.Count; i++)
                        {
                            if (gp[i].Success)
                            {
                                string tmp = gp[i].Value;
                                Regex r2 = new Regex(@"\w{40}");
                                if (r2.IsMatch(tmp))
                                {
                                    //获取HASH
                                    tmp = r2.Match(tmp).Value;

                                    //恢复UT下载
                                    string d = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&action=recheck&hash={2}", url, uttoken, tmp), ref utcookie, username, password);
                                    d = WebAccess.GetWebResponse(string.Format("{0}gui/?token={1}&action=start&hash={2}", url, uttoken, tmp), ref utcookie, username, password);

                                    if (d.IndexOf("{\"build\":") >= 0)
                                    {
                                        //WorkLog.Add(9, string.Format("重新校验并恢复UT下载，HASH值为{0}", tmp));
                                        return;
                                    }
                                    else WorkLog.Add(3, "重新校验并恢复UT下载失败1");
                                }
                                else WorkLog.Add(3, "重新校验并恢复UT下载失败2");
                            }
                            else WorkLog.Add(3, "重新校验并恢复UT下载失败3");
                        }
                    }
                    return;
                }
                else
                {
                    WorkLog.Add(3, "读取UT种子列表信息失败");
                }
            }
            return;

        }
    }
}
